package com.chenchao.javafile;

import java.io.*;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/19 14:49
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javafile.Test13.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 数据流
 */
public class Test13 {
    public static void main(String[] args) throws IOException {
        //test1();
        test2();
    }

    /**
     * 使用字节数组流对数据流进行测试
     * @throws IOException IO异常
     */
    public static void test1() throws IOException {
        byte[] b;
        //这里的b内存相当于要处理的文件
        //写入
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(byteArrayOutputStream));
        dataOutputStream.writeUTF("show time");
        dataOutputStream.writeChar('A');
        dataOutputStream.writeInt(1);
        dataOutputStream.writeBoolean(false);

        dataOutputStream.close();
        //一定要先关闭数据流再取出数组
        b = byteArrayOutputStream.toByteArray();
        System.out.println("输入数组长度为"+b.length);
        //把写入的源头变成字节数组


        //读出
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(b);
        DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(byteArrayInputStream));
        //读出的顺序一段要和写入的顺序一样
        String s = dataInputStream.readUTF();
        char c = dataInputStream.readChar();
        int i = dataInputStream.readInt();
        boolean b1 = dataInputStream.readBoolean();
        System.out.println(s);
        System.out.println(c);
        System.out.println(i);
        System.out.println(b1);
    }

    /**
     * 使用文件对数据流进行测试
     * @throws IOException IO异常
     */
    public static void test2() throws IOException {
        //写入
        DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream
                (new FileOutputStream("myjava01/src/fo/a2.txt")));
        dataOutputStream.writeUTF("show time again");
        dataOutputStream.writeInt(9);
        dataOutputStream.writeBoolean(false);
        dataOutputStream.close();

        //读出,注意一定要按顺序
        DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream
                (new FileInputStream("myjava01/src/fo/a2.txt")));
        System.out.println(dataInputStream.readUTF());
        System.out.println(dataInputStream.readInt());
        System.out.println(dataInputStream.readBoolean());
    }
}
